package com.github.permissiondog.cancanpandroid.ui.view;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.preference.CheckBoxPreference;
import androidx.preference.DropDownPreference;
import androidx.preference.EditTextPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;

import com.github.permissiondog.cancanpandroid.MyApplication;
import com.github.permissiondog.cancanpandroid.R;
import com.github.permissiondog.cancanpandroid.repository.impl.LocalRepositoryImpl;
import com.github.permissiondog.cancanpandroid.repository.impl.UserRepositoryImpl;

import java.util.prefs.PreferenceChangeListener;

public class SettingsFragment extends PreferenceFragmentCompat implements Preference.OnPreferenceChangeListener {

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.root_preferences, rootKey);
        var username = findPreference("username");
        var nickname = findPreference("nickname");
        var role = findPreference("role");
        var logout = findPreference("logout");

        UserRepositoryImpl.getInstance().currentUser(user -> user.ifPresent(u -> {
            username.setSummary(u.getUsername());
            role.setSummary(u.getRole().getDisplayName());
            nickname.setSummary(u.getNickname());
        }));

        logout.setOnPreferenceClickListener(preference -> {
            UserRepositoryImpl.getInstance().logout(() -> {
                startActivity(new Intent(getActivity(), LoginActivity.class));
                Toast.makeText(getActivity(), "登出成功", Toast.LENGTH_LONG).show();
                getActivity().finish();
            });
            return true;
        });
    }

    @Override
    public boolean onPreferenceChange(@NonNull Preference preference, Object newValue) {
        return false;
    }
}



